package com.lovetemperature.service.impl;

import java.util.Date;
import java.util.List;

import com.lovetemperature.dao.Dao;
import com.lovetemperature.model.Member;
import com.lovetemperature.model.MemberState;
import com.lovetemperature.service.MemberService;

public class MemberServiceImpl implements MemberService{
	private Dao<Member> memberDao;
	
	@Override
	public Member login(String account, String password) {
		List<Member> result = memberDao.findByField("email", account);
		if(result==null || result.size()==0){
			return null;
		}else if(result.get(0).getPassword().equals(password)){
			return result.get(0);
		}
		return null;
	}

	public Dao<Member> getMemberDao() {
		return memberDao;
	}

	public void setMemberDao(Dao<Member> memberDao) {
		this.memberDao = memberDao;
	}

	@Override
	public boolean register(Member member) {
		List<Member> origin = memberDao.findByField("email", member.getEmail());
		if(origin!=null && origin.size()!=0){
			return false;
		}else {
			member.setState(MemberState.未激活);
			memberDao.save(member);
			return true;
		}
	}

	@Override
	public boolean update(Member member) {
		memberDao.update(member);
		return true;
	}

	@Override
	public List<Member> findAllMember() {
		return memberDao.findAll();
	}

	@Override
	public Member findById(Long memberId) {
		return memberDao.findById(memberId);
	}

	@Override
	public void addMember(Member member) {
		memberDao.save(member);
	}

	@Override
	public void recharge(Member member, double rechargeNum) {
		member.setBalance(member.getBalance()+rechargeNum);
		Date today = new Date();
		Date oneYaerLater = new Date();
		long afterTime=(today.getTime()/1000)+60*60*24*365;
		oneYaerLater.setTime(afterTime*1000);
		member.setLastPay(today);
		member.setUntilDate(oneYaerLater);
		if(member.getState().equals(MemberState.未激活) && rechargeNum >= 100){
			member.setState(MemberState.已激活);
		}
		this.update(member);
	}
}
